package com.easysoft.framework.action;
import com.easysoft.commons.utils.*;
import com.easysoft.framework.annotation.logs.SystemControllerLog;
import com.easysoft.framework.beans.Page;
import com.easysoft.framework.role.model.SysRole;
import com.easysoft.framework.role.model.SysRoleQuery;
import com.easysoft.framework.role.model.SysRoleView;
import com.easysoft.framework.role.model.UserRole;
import com.easysoft.framework.role.service.RoleService;
import com.easysoft.framework.role.service.UserRoleService;
import com.easysoft.framework.user.model.SysUser;
import com.easysoft.framework.user.model.SysUserQuery;
import com.easysoft.framework.user.model.SysUserView;
import com.easysoft.framework.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;

/**
 * Created by try on 2017/7/5.
 */
@RestController
@RequestMapping(value = SystemUserAction.BASE_VIEW)
public class SystemUserAction {
    public static final String BASE_VIEW = "/user";
    private final static Logger logger = LoggerFactory.getLogger(SystemUserAction.class);

    @Autowired
    @Qualifier("service.UserService")
    private UserService userService;

    @Autowired
    @Qualifier("service.SysRoleService")
    private RoleService roleService;

    @Autowired
    @Qualifier("service.UserRoleService")
    private UserRoleService userRoleService;

    /**
     * 用户列表
     *
     * @param page 分页条件
     * @param query 查询条件
     * @return 返回用户的结果集合
     */
    @RequestMapping(value = "/listUser",method = RequestMethod.GET)
    public ModelAndView listUser(Page page, SysUserQuery query) {

        logger.info("Call SystemUserAction.listUser({},{})", page.toString(), query.toString());

        List<SysUserView> listUser = userService.selectSysUserListByPage(query,page);

        ModelAndView mv = new ModelAndView(BASE_VIEW + "/listUser");
        mv.addObject("page", page); // 返回分页
        mv.addObject("query", query);// 查询条件
        mv.addObject("listUser", listUser); // 返回查询结果集
        return mv;
    }

    @RequestMapping(value = "/editUser",method = RequestMethod.GET)
    public ModelAndView editUser(String action, @RequestParam(required = false) String id){
        logger.info("Call SystemUserAction.editManager({},{})", action, id);
        ModelAndView mv = new ModelAndView(BASE_VIEW + "/editManager");
        SysRoleQuery query = new SysRoleQuery();
        query.setPrefix("u:");
        List<SysRoleView> roles = roleService.selectSysRoleList(query);
        mv.addObject("roles", roles);
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("add")) {
            // 添加
            if (StringUtils.isNotNullAndBlank(id)) {
                return null;
            }
            return mv;
        }
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("update")) {
            // 修改
            if (StringUtils.isNullOrBlank(id)) {
                return null;
            }
            SysUserView entity = userService.selectSysUserViewById(id);
            if (entity == null) {
                return null;
            }
            mv.addObject("entity", entity);
            return mv;
        }
        return null;
    }

    @RequestMapping(value = "/saveUser",method = RequestMethod.POST)
    public int saveUser(String action, SysUser sysUser, String roleId, @RequestParam(value="multipartFile", required=false)MultipartFile multipartFile, HttpServletRequest request, HttpSession session){
        logger.info("Call SystemUserAction.saveManager({},{},{})", action, sysUser.toString(), roleId);
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("add")) {
            // 添加
            if (StringUtils.isNotNullAndBlank(sysUser.getId())) {
                return 0;
            }
            return addSysUser(sysUser, roleId, multipartFile, request, session);
        }
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("update")) {
            // 修改
            if (StringUtils.isNullOrBlank(sysUser.getId())) {
                return 0;
            }
            return updateSysUser(sysUser, roleId, multipartFile, request, session);
        }
        return 0;
    }

    /**
     * 添加用户
     *
     * @param sysUser
     * @return
     */
    @SystemControllerLog(description = "新增用户信息")
    public int addSysUser(SysUser sysUser,String roleId, @RequestParam(value="multipartFile", required=false)MultipartFile multipartFile, HttpServletRequest request,HttpSession session) {
        logger.info("Call SystemUserAction.addSysUser({})", sysUser.toString());
        if (StringUtils.isNullOrBlank(sysUser.getUserName()) || StringUtils.isNullOrBlank(sysUser.getPassword()) || StringUtils.isNullOrBlank(sysUser.getMobile())) {
            // 用户名或密码或手机号为空
            return 0;
        }
        int count = userService.countUserByUserNameOrMobile(sysUser.getUserName(), sysUser.getMobile());
        if (count > 0) {
            // 用户名或手机号已存在
            return 2;//手机号存在
        }

        SysRole sysRole = roleService.selectSysRoleById(roleId);
        if (sysRole == null){
            return 0;
        }

        String salt = RandomUtils.getSpecialChart(4);
        sysUser.setSalt(salt);
        sysUser.setPassword(DigestUtils.md5DigestAsHex((sysUser.getPassword() + salt).getBytes(Charset.forName("utf-8"))));
        sysUser.setSysType(1);

        if(multipartFile != null && !("").equals(multipartFile)){
            sysUser.setHeadImage( FileUtils.savePicture(multipartFile,"user",request));
        }

        int flag = userService.addSysUser(sysUser);

        if (flag == 1){
            UserRole userRole = new UserRole();
            userRole.setUserId(sysUser.getId());
            userRole.setRoleId(sysRole.getId());
            userRole.setOperator((String) session.getAttribute(WebConstants.SESSION_USER_ID));
            flag = userRoleService.addUserRole(userRole);
        }

        if (flag == 1) {
            return 1;
        } else {
            userService.deleteSysUser(sysUser.getId());
            return 0;
        }
    }

    /**
     * 修改用户
     *
     * @param sysUser
     * @return
     */
    @SystemControllerLog(description = "修改用户信息")
    public int updateSysUser(SysUser sysUser, String roleId, @RequestParam(value="multipartFile", required=false)MultipartFile multipartFile, HttpServletRequest request, HttpSession session) {
        logger.info("Call SystemUserAction.updateSysUser({})", sysUser.toString());
        SysUserView temp = userService.selectSysUserViewById(sysUser.getId());
        if (temp == null){
            return 0;
        }

        if (StringUtils.isNullOrBlank(sysUser.getUserName()) || StringUtils.isNullOrBlank(sysUser.getPassword()) || StringUtils.isNullOrBlank(sysUser.getMobile())) {
            // 用户名或密码或手机号为空
            return 0;
        }

        sysUser.setUserName(temp.getUserName());

        if (!sysUser.getPassword().equals(temp.getPassword())){
            String salt = RandomUtils.getSpecialChart(4);
            sysUser.setSalt(salt);
            sysUser.setPassword(DigestUtils.md5DigestAsHex((sysUser.getPassword() + salt).getBytes(Charset.forName("utf-8"))));
        }

        if(multipartFile != null && !("").equals(multipartFile)){
            sysUser.setHeadImage( FileUtils.savePicture(multipartFile,"user",request));
        }

        if (!temp.getRoleId().equals(roleId)){
            userRoleService.deleteUserRoleByUserId(sysUser.getId());
            UserRole userRole = new UserRole();
            userRole.setUserId(sysUser.getId());
            userRole.setRoleId(roleId);
            userRole.setOperator((String) session.getAttribute(WebConstants.SESSION_USER_ID));
            userRoleService.addUserRole(userRole);
        }
        int flag = userService.updateSysUserById(sysUser);

        if (flag == 1) {
            return 1;
        }

        return 0;
    }

    @SystemControllerLog(description = "删除用户信息")
    @RequestMapping(value = BASE_VIEW + "/deleteManager", method = RequestMethod.POST)
    public String deleteSystemManager(String id) {
        logger.info("Call SystemManagerAction.deleteSystemManager({})", id);
        SysUser user = userService.selectSysUserByUserId(id);
        if (user == null) {
            // 管理员不存在
            return "0";
        }

        int flag = userService.deleteSysUser(id);
        if (flag == 1) {
            userRoleService.deleteUserRoleByUserId(id);
            // 删除成功
            return "1";
        }
        // 删除失败
        return "0";
    }
}
